package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"user-manger-system/cache"
	"user-manger-system/models"
	"user-manger-system/pkg"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名 或者 密码为空",
		}
		c.ServeJSON()
		return
	}
	//密码错误三次，禁止登录
	loginErrorRedisKey := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, loginErrorRedisKey).Int()
	if errCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误3次禁止登录",
		}
		c.ServeJSON()
		return
	}

	var err error
	var user models.User
	err = models.DB.Table("users").Where("username = ?", username).First(&user).Debug().Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户查询失败",
		}
		c.ServeJSON()
		return
	}

	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5Str(password) {

		cache.Rdb.Incr(cache.Ctx, loginErrorRedisKey)                        //自增+1
		pwdCountErr, _ := cache.Rdb.Get(cache.Ctx, loginErrorRedisKey).Int() //错误3次了
		if pwdCountErr == 3 {
			cache.Rdb.Set(cache.Ctx, loginErrorRedisKey, 3, time.Hour*2)
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "密码错误次数3次，封禁2个小时",
			}
			c.ServeJSON()
			return
		}

		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}

	cache.Rdb.Del(cache.Ctx, loginErrorRedisKey) //清空错误次数
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
	}
	c.ServeJSON()
	return

}

func (c *UserController) List() {
	fmt.Println("List")

	//1-从redis读取数据
	dataListKey := "data_list"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, dataListKey).Result()

	var user []models.User
	if cacheJson == "" {

		//1-从mysql读取数据
		models.DB.Model(&models.User{}).Find(&user)
		//2-数据保存到redis
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, dataListKey, jsonData, time.Hour*2)
	} else {
		//从redis得到数据
		err := json.Unmarshal([]byte(cacheJson), &user)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "缓存数据读取失败",
			}
			c.ServeJSON()
			return
		}
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": user,
		"msg":  "success",
	}
	c.ServeJSON()
	return

}

func (c *UserController) Detail() {
	fmt.Println("Detail")

	id, _ := c.GetInt("id")

	//从缓存中查询数据
	dataListKey := "data_id_" + strconv.Itoa(id)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, dataListKey).Result()
	var user models.User
	if cacheJson == "" {
		//从mysql查询数据
		models.DB.Model(&models.User{}).Where("id=?", id).First(&user)
		//redis保存数据
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, dataListKey, jsonData, time.Hour*2)
	} else {
		//从redis得到数据
		err := json.Unmarshal([]byte(cacheJson), &user)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "缓存数据读取失败",
			}
			c.ServeJSON()
			return
		}
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": user,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}
